# coding:utf-8
# 使用线程Thread对象的Lock和Rlock可以实现简单的线程同步
# 这两个对象都有acquire方法和release方法
# 对于那些需要每次只允许一个线程操作的数据，可以将其操作放到acquire和release之间

import threading
import time

thread_lock = threading.Lock()


def print_time(thread_name, counter, delay):
    while counter:
        time.sleep(delay)
        print("%s:%s" % (thread_name, time.ctime(time.time())))
        counter -= 1


class my_thread(threading.Thread):

    def __init__(self, thread_id, thread_name, counter):
        threading.Thread.__init__(self)
        self.thread_id = thread_id
        self.thread_name = thread_name
        self.counter = counter

    def run(self):
        print("开启线程" + self.thread_name)
        # 获取锁，用于线程同步
        thread_lock.acquire()
        print_time(self.thread_name, self.counter, 3)
        # 释放锁，开启下一个线程
        thread_lock.release()


threads = []
thread_1 = my_thread(1, "Thread-1", 4)
thread_2 = my_thread(2, "Thread-2", 4)

thread_1.start()
thread_2.start()

threads.append(thread_1)
threads.append(thread_2)

for thread in threads:
    thread.join()

print("退出主线程")
